import React, { useState } from 'react'
import PageHeader from '../components/PageHeader'
import { Image, Form, Input, Button, Toast } from 'antd-mobile'
import logo from '../assets/imgs/logo-myzx.png'
import { getMsgCode, login } from '../utils/api'
import { useRouterHook } from '../utils/hooks'
const Login: React.FC = () => {
    const { navigate } = useRouterHook()
    const [phone, setPhone] = useState('')
    const onSubmit = async (values: { phone: string, msgCode: string }) => {
        // console.log('onSubmit', values);
        const { data } = await login({ ...values })
        if (data.code === 200) {
            // console.log(data, 'data');
            // 将登录信息写入本地存储
            localStorage.setItem('userLoginInfo', JSON.stringify(data.data))
            Toast.show({ icon: 'success', content: data.msg })
            // 自动跳转到会员中心页面
            navigate('/my')
            return
        }
        Toast.show({ icon: 'fail', content: data.msg })
    }
    // 倒计时状态， 是否已经开始倒计时， 
    const [start, setStart] = useState(false)
    // 倒计时秒数
    let [second, setSecond] = useState(10)
    const sendMsgCode = () => {
        const regPhone = /^1[3456789]\d{9}$/
        if (!regPhone.test(phone)) {
            Toast.show('手机号码不合法')
            return false
        }
        setTimeout(async () => {
            const { data } = await getMsgCode(phone)
            if (data.code === 200) {
                Toast.show(data.data)
            }
        }, 3000)

        return true
    }

    // 倒计时
    // 保存定时器id
    let timeId: any = 0
    const countDown = async () => {
        if (!await sendMsgCode()) {
            return false
        }
        setStart(true)  // 开始倒计时
        timeId = setInterval(() => {
            second -= 1
            setSecond(second)    // 异步方法
            if (second <= 0) {
                clearInterval(timeId)       // 清除定时器
                setStart(false)      // 重置状态start
                setSecond(10)        // 重置倒计时起始值
            }
        }, 1000);
    }
    return (
        <div>
            <PageHeader><h3>会员登录</h3></PageHeader>
            <Image src={logo} width={'50%'} style={{ margin: '20px auto' }}></Image>
            <Form onFinish={onSubmit} layout='horizontal' mode='card'
                footer={
                    <Button shape="rounded" block color='primary' type="submit" size="middle">
                        立即登录
                    </Button>
                }
            >
                <Form.Item name="phone" label='手机号码'
                    rules={[{ required: true, message: '请输入11位合法位手机号码', validateTrigger: "blur" }]} >
                    <Input value={phone} onChange={val => setPhone(val)} placeholder='请输入11位手机号码' maxLength={11} />
                </Form.Item>
                <Form.Item name="msgCode" label='短信验证码'
                    extra={start ? <a>{`${second}s后重新发送`}</a> : <a onClick={countDown}>发送验证码</a>}
                    rules={[{ required: true, message: '请输4位短信验证码' }]} >
                    <Input placeholder='请输入短信验证码' />
                </Form.Item>
            </Form>

        </div>
    )
}
export default Login
